module Syspec
  class Reporter

    attr_accessor :stdout, :stderr, :options
    attr_accessor :value, :time

    def initialize(options = {})
      self.options = {}
      self.stdout = STDOUT
      self.stderr = STDERR
    end
    
    def notify(key, options = {})
      @time = MicroBench.time { @value = yield }
      send(key, @value)
      @value || key
    end
    
    def header(*args)
      heading = "%-40s %6s %7s %6s %8s" % %w(URL Bytes Time Code Status)
      puts heading.underline.bold
    end

    def new_task(domain)
      fprint "\nChecking #{domain}... ".bold.cyan
    end
    
    def domain_exists(boolean)
      puts boolean ? "exists.".bold.cyan : "does not exist!".bold.red
    end

    def request(uri)
      if uri.path.size > 40
        puts uri.path
        fprint "%40s " % [""]
      else
        fprint "%-40s " % [uri.path]
      end
    end

    def response(obj)
      fprint "%6d %6.2fs %6d   " % [obj.body.size, @time, obj.code]
    end

    def passed?(boolean)
      puts boolean ? "PASSED".bold.green : "FAILED".bold.magenta
    end
    
    def individual_results(results, show_passed = true)
      results.each do |(key, condition, result)|
        next if !show_passed && result
        colours = result ? [:bold, :green] : [:bold, :magenta]
        fprint "%2s %-13s " % ["", "response #{key}:".with_ansi(*colours)]
        puts condition.to_verbose
      end
    end

    def puts(message)
      stdout.puts message
    end

    def fprint(message)
      stdout.print message; stdout.flush
    end

  end
end